import logging
import traceback

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
from app.core.config import settings
logger=logging.getLogger(__name__)

engine = create_engine(settings.get_database_url)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()
        logger.info("db closed")


def db_action(_fun):
    db: Session= next(get_db())
    try:
        return _fun(db)
    except (Exception) as e:
        # logger.exception(f'{str(e)} %s')  # 自动包含堆栈
        # logger.warning(f'{str(e)}',e)
        # logger.warning(f'{str(e)}', exc_info=True)
        # traceback.print_exc()
        # logger.warning(f'{str(e)} %s',"".join(traceback.format_stack()))
        # stack=traceback.format_stack(limit=3)
        # logger.warning(f'{str(e)} %s',"".join(stack))
        logger.warning(f'{str(e)} ')
        pass
    finally:
        try:
            db.close()
        except Exception as e1:
            pass


def db_close(db:Session):
    try:
        db.close()
    except Exception as e1:
        pass
